#!usr/bin/env python
# -*- coding:utf-8 -*-
# user nanme: Mr.zhang
# data1 time : 2022/3/8   11:44 上午
# project   : monitor.py
# IDE       : PyCharm
# email     :17600960626@163.com

import datetime
import json
import os
import time
from time import strftime,localtime
import re
from lib.read_file import Corpus
from public.dev_log import log_cat
from lib.read_sql import db
import requests

read_text=Corpus()

Url = '***************1'#钉钉openapi
HEADERS = {"Content-Type": "application/json ;charset=utf-8 "}
log_path = "/report"

class Times():

    def log_mun(self):
        '''提取日志时间和pid'''
        self.timeouts = []
        self.timecorrect = []
        for logs in read_text.read_log(log_path):
            with open(logs,'r',encoding='utf-8') as file:
                file_content = file.readlines()
                if len(file_content)!=0:
                    file_line_last = file_content[-1]
                    target = file_line_last[:60]
                    log_data = re.findall('\d{2}-\d{2} \d{1,2}:\d{1,2}:\d{1,2}',target) #正则提取日期
                    # pid = re.findall('\s\s\d{1,4}\s\s',target)  # 正则提取pid
                    log_datas = ['2022-'+(i) for i in log_data]
                    log_times = "".join(log_datas)
                    # pids = [str(j)for j in pid]
                    # pid_id = "".join(pids)
                    d1=datetime.datetime.strptime(log_times,'%Y-%m-%d %H:%M:%S')#日志时间
                    times = strftime("%Y-%m-%d %H:%M:%S", localtime())#当前时间
                    d2 = datetime.datetime.strptime(times, '%Y-%m-%d %H:%M:%S')
                    self.devices = re.findall('.*report/(.*?)-',logs)
                    number = re.findall('.*-(.*)-.*',logs) #获取设备编号
                    time.sleep(0.5)
                    print(d2,d1)
                    diff=(d2-d1).seconds #时间差
                    print(diff,11111)
                    if diff > 300:#超时
                        sql = 'UPDATE dev_table SET code = 2 WHERE devices="%s"' % self.devices
                        db.updateDb(sql)
                        self.timeouts.append(number)
                        self.timeouts.append(self.devices)
                        self.timeouts.append(diff)

                    else:#正常
                        self.timecorrect.append(number)
                        self.timecorrect.append(self.devices)
                        self.timecorrect.append(diff)
        print(self.timeouts,222)
        return self.timeouts,self.timecorrect


    def ding_message(self):
        if len(self.timeouts) !=0:
            mags = '💣💣💣💣💣💣💣💣️\n😈监控报警：设备状态异常\n列表说明：【编号，devices，运行时间】\n%s' \
                   '\n更新库中设备状态为异常，大哥快来处理👻\n💣💣💣💣💣💣💣💣️' %self.timeouts

            String_textMsg = { "msgtype": "text",
                               "text": {
                                   "content": mags
                               },
                               "at":{
                                   "atMobiles":['+86-17600960626'],
                                   "isAtAll":False
                               }
                               }
            String_textMsgs = json.dumps(String_textMsg)
            res = requests.post(Url, data=String_textMsgs, headers=HEADERS)
            # print(res.text)
            os.system('adb kill-server')
            os.system('adb start-server')
        else:
            pass
        # os.system('adb kill-server')
        '''运行正常检查--暂时不开启'''
        # mag = '运行检查--设备运行正常的数据列表：\n【编号，devices，运行时间】\n%s' %self.timecorrect
        # String_textMsg1 = {"msgtype": "text",
        #                    "text": {
        #                        "content": mag
        #                    },
        #                    "at": {
        #                        "atMobiles": ['+86-17600960626'],
        #                        "isAtAll": False
        #                    }
        #                    }
        # String_textMsgs1 = json.dumps(String_textMsg1)
        # ress = requests.post(Url, data1=String_textMsgs1, headers=HEADERS)
        # print(ress.text)

a=Times()
log_cat.sql_dev()
log_cat.rm_log()
log_cat.cmd_log()
a.log_mun()
# a.ding_message()